package com.lws.basic.utils.common;

import android.os.Handler;
import android.os.Message;



public class LoopUtils {
    /**
     * 利用Handler实现周期执行,   目前只支持在主线程调用
     * @param runnable   需要周期执行的任务对象
     * @param taskInterval  周期间隔时间
     * @return  返回周期执行所用的Handler, 当需要停止时只需要执行   hander.removeMessages(0) 方法
     */
    public static Handler pollingHandler(final Runnable runnable, final long taskInterval) {
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Message message = Message.obtain();
                Runnable runnable1 = (Runnable)msg.obj;
                runnable1.run();
                message.obj = msg.obj;
                sendMessageDelayed(message,taskInterval);
            }
        };
        Message message = Message.obtain();
        message.obj = runnable;
        handler.sendMessageDelayed(message,taskInterval);
        return handler;
    }

    /**
     * 利用Handler实现周期执行,   目前只支持在主线程调用,
     * @param runnable   需要周期执行的任务对象
     * @param taskInterval  周期间隔时间
     * @return  返回周期执行所用的Handler, 当需要停止时只需要执行   hander.removeMessages(0) 方法
     */
    public static Handler pollingHandler(final long preWait,final Runnable runnable, final long taskInterval) {
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Message message = Message.obtain();
                Runnable runnable1 = (Runnable)msg.obj;
                runnable1.run();
                message.obj = msg.obj;
                sendMessageDelayed(message,taskInterval);
            }
        };
        Message message = Message.obtain();
        message.obj = runnable;
        handler.sendMessageDelayed(message,preWait);
        return handler;
    }
}
